﻿/* 
 *  <copyright file="InvertMoverDirOnColCmp.cs" company="Wesley Jowitt">
 *  
 *  SobrietyEngine: Copyright (c) 2011 Wesley Jowitt
 *  
 *  This software is distributed under a software license.
 *   * As of the creation time of this file, the license in use is the Microsoft Permissive License (Ms-PL) 
 *    * The license can be viewed at:
 *     * License.Txt in the root folder of this project
 *      * http://sobrietyengine.codeplex.com/license
 *       * http://www.microsoft.com/opensource/licenses.mspx
 *       
 *  </copyright>
 *   */

using System;
using System.Collections.Generic;

using Microsoft.Xna.Framework;

using FarseerPhysics;
using FarseerPhysics.Collision;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Dynamics.Contacts;

using SobrietyEngine.Guids;
using SobrietyEngine.Components;
using SobrietyEngine.Actor;
using SobrietyEngine.Logging;

namespace SobrietyEngine.Components.Physics.OnCollision
{
    public class InvertMoverDirOnColCmp: OnCollisionBase
    {
        Boolean OnlyOnStatic { get; set; }
        IMovement mover;


        /// <summary>
        /// value used to determin our tolerance for what constitutes a wall when we
        /// get the dot product of a collision and our direction
        /// </summary>
        float dotTolerance = -0.5f;

        public InvertMoverDirOnColCmp()
            : base()
        {
            OnlyOnStatic = false;
        }

        public InvertMoverDirOnColCmp(float collisionDirectionDotLimit)
            : this()
        {
            dotTolerance = collisionDirectionDotLimit;
        }

        public override bool InitComponent()
        {
            if (!base.InitComponent())
                return false; //delay

            mover = Actor.Get<IMovement>();
            if (mover == null)
                Logger.Error(this, "Couldnt find provider of IMover");

            return true;
        }

        override public bool OnCollision(Fixture f1, Fixture f2, Contact contact)
        {
            //filter out actors we dont want trigger on
            IActor other = (IActor)f2.Body.UserData;

            if (OnlyOnStatic && f2.Body.BodyType != BodyType.Static)
                return true; //collision happened, but we dont invert our movers dir

            //w want to invert when we hit something in our way
            Vector2 normal;
            FarseerPhysics.Common.FixedArray2<Vector2> fa = new FarseerPhysics.Common.FixedArray2<Vector2>();
            contact.GetWorldManifold(out normal, out fa);

            //see if we smacked into a wall
            float dot = Vector2.Dot(normal, mover.Dir);

            //if we hit something opposite our direction, invert!
            if(dot < dotTolerance)
                mover.Dir = mover.Dir * -1;
                       
            return true;
        }   
    }
}
